package com.gyms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVProductInfoBean;
import com.classic.okhttp.beans.HVProductTypeInfoBean;
import com.classic.okhttp.beans.HVProductTypeItemBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IProductService;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.adapter.ProductDetailsAdapter;
import com.gyms.animotion.CollectAnimotion;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.DataCenter;
import com.gyms.manager.TitleManager;
import com.gyms.view.bottomview.ShareDialog;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import constant.EventConstant;
import constant.PicSplit;
import glide.ImageLoaderUtils;
import utils.ActivityUtils;
import utils.DateUtil;
import utils.DecimalUtils;
import utils.StringUtils;
import weight.ComDialog;
import weight.ExpandableTextView;
import weight.UiEvent;

/**
 * 产品详情
 * yjl
 */
public class ProductDetailsActivity extends MyAutoLayoutActivity implements View.OnClickListener, ProductDetailsAdapter.DoProductMustPay {
    @BindView(R.id.lv_product)
    ListView lvProduct;
    @BindView(R.id.iv_img_right)
    ImageView mIvImgCollect;//收藏按钮

    @BindView(R.id.iv_img_right_right)
    ImageView mIvShare;//分享按钮

    private TextView mTvProjectName;//项目名称
    private View mHeader;
    private LinearLayout mLinearLayout, mAddressLayout;
    private ProductDetailsAdapter mProductAdapter;

    ExpandableTextView mTvNoticeMore;

    private String productId = "";

    private ImageView mProductCover, mHuiImage;
    private TextView mtitle, mPrise, mAddress, mAddressDetail, mHuiText;
    private HVProductInfoBean mResponse;//产品

    private Animation animation;

    private List<String> mImageList;//点击产品头像跳转的相册List

    private String mShortAddress;//短的地址

    private ImageView ivCoverIcon;//显示相册的图标

    private List<HVProductTypeItemBean> mListData=new ArrayList<>();

    private TextView mTvTimeEnd;//产品截止日期

    //对活动开始时间的处理

    public int mCurServiceTime;//服务器传来的时间 s
    public int mCurLocationTime;//本地的当前时间  s

    private ShareDialog mShareDialog;
    private String mProjectName;//运动名称

    private String mGymName;//场馆名称
    private Double minPrice;//最低金额
    private Double maxPrice;//最高金额

    //可退款标签相关
    private TextView mTvRefund;
    private ImageView mIvRefundIcon;

    private CollectAnimotion mCollectAnimotion;
    private android.os.Handler mHandler=new android.os.Handler();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_product_details;
    }

    @Override
    protected void initView() {
        initData();
        createLoadingView("加载中", true);
        productId = getIntent().getStringExtra(Constants.FALG_INTENT_PRPDUCT_ID);
        setBack();
        mHeader = LayoutInflater.from(mContext).inflate(R.layout.head_product_details, null);
        mLinearLayout = (LinearLayout) mHeader.findViewById(R.id.set_visible);
        mAddressLayout = (LinearLayout) mHeader.findViewById(R.id.ll_gym_adress);
        mProductCover = (ImageView) mHeader.findViewById(R.id.iv_product_cover);
        ivCoverIcon = (ImageView) mHeader.findViewById(R.id.iv_cover_icon);
        mHuiImage = (ImageView) mHeader.findViewById(R.id.tv_discount);
        mHuiText = (TextView) mHeader.findViewById(R.id.tv_product_hui);
        mtitle = (TextView) mHeader.findViewById(R.id.tv_product_title);
        mPrise = (TextView) mHeader.findViewById(R.id.tv_product_prise);
        mAddress = (TextView) mHeader.findViewById(R.id.tv_address_title);
        mAddressDetail = (TextView) mHeader.findViewById(R.id.tv_address_detil);
        mTvTimeEnd = (TextView) mHeader.findViewById(R.id.tv_time_end);
        mTvProjectName = (TextView) mHeader.findViewById(R.id.tv_project_name);
        mTvNoticeMore = (ExpandableTextView) mHeader.findViewById(R.id.expand_text_view);

        mTvRefund = (TextView) mHeader.findViewById(R.id.tv_refund_text);
        mIvRefundIcon = (ImageView) mHeader.findViewById(R.id.iv_refund);
        lvProduct.addHeaderView(mHeader);
        animation = AnimationUtils.loadAnimation(this, R.anim.applaud_animation);
        mTitleManager.setRightViewR(R.mipmap.icon_fenxiang);
        initProDetailAdapter();
    }

    private void initData() {
        mCollectAnimotion =new CollectAnimotion(mHandler,mIvImgCollect);
    }

    /**
     * 初始化详情列表adapter
     */

    private void initProDetailAdapter() {
        mProductAdapter = new ProductDetailsAdapter(mContext,mListData, loadingView);
        mProductAdapter.setDoProductMustPay(this);
        lvProduct.setAdapter(mProductAdapter);

    }

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected void setListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
        mProductCover.setOnClickListener(this);
        mIvImgCollect.setOnClickListener(this);
        mIvShare.setOnClickListener(this);
    }

    @Override
    protected void processLogic() {
        getProductDetails(false);
    }

    /**
     * 请求产品详情
     * @param isRefresh 是否刷新
     */
    private void getProductDetails(final boolean isRefresh) {
        loadingView.show();
        IProductService.getProductTypeInfo(this, productId, false, new ObjectCallback<HVProductTypeInfoBean>() {
            @Override
            public void onSuccess(HVProductTypeInfoBean response, String message) {
                dialogDis();
                doFullView(response,isRefresh);
            }

            @Override
            public void onErrorT(int code, HVProductTypeInfoBean response, String errorMessage) {
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * 填充数据
     */
    private void doFullView(HVProductTypeInfoBean response, boolean isRefresh) {
        if (null == response || !response.getBaseInfo().getOnShelf()) {//response为null 就finish  代表下架
            ToastUtil.showToast(mContext, "该课程不存在或已下架");
            finish();
            return;
        }


        if (!StringUtils.isNull(response) && !StringUtils.isNull(response.getBaseInfo())) {
            mResponse = response.getBaseInfo();
            // 可退款标签
            //是否可退款
            changeButton(isRefresh);
            if(isRefresh){//只刷新收藏的状态
                return;
            }
            mIvRefundIcon.setVisibility(mResponse.refundable?View.VISIBLE:View.GONE);
            mTvRefund.setVisibility(mResponse.refundable?View.VISIBLE:View.GONE);
            if(mResponse.refundable){
                ImageLoaderUtils.display(mContext,mIvRefundIcon, PicSplit.urlAdd(Cons.S_PRODUCT_REFUND_ICON,PicSplit.TYPE_TAB));
            }
            mCurServiceTime=response.serverTS;
            mCurLocationTime=DateUtil.getCurTimeS();
            mTvTimeEnd.setText("有效截止日期："+ DateUtil.getSimpleDateNoSD(mResponse.getValidityEndTime()));
            mImageList=mResponse.getImageList();
            if(StringUtils.isNull(mImageList)){//如果没有相册就隐藏
                ivCoverIcon.setVisibility(View.GONE);
            }
            mShortAddress=mResponse.getShortAddress();
            dofullCount();
            mProjectName=response.getBaseInfo().getProjectName();
            mTvProjectName.setText(mProjectName);
            mtitle.setText(StringUtils.CS(mResponse.getProductName()));
            mGymName=mResponse.getVenueName();
            mAddress.setText(StringUtils.CS(mGymName));
            mAddress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle mBundle = new Bundle();
                    mBundle.putString(Constants.FLAG_INTENT_VENUEID, mResponse.getVenueId());
                    startActivity(GymDetailActivity.class, mBundle, false);
                }
            });
            mAddressDetail.setText(StringUtils.CS(mResponse.getAddress()));
             minPrice=mResponse.getMinPrice();
             maxPrice=mResponse.getMaxPrice();
            if (!StringUtils.isNull(minPrice) && !StringUtils.isNull(maxPrice)) {
                if (minPrice.compareTo(maxPrice) == 0) {
                    mPrise.setText( DecimalUtils.setPriceStyle(mContext,minPrice,R.dimen.price_text_size_14,R.dimen.price_text_size_12,true));
                } else {
                    mPrise.setText(DecimalUtils.setPriceStyle(mContext,minPrice,R.dimen.price_text_size_14,R.dimen.price_text_size_12,true).append(" - ").append( DecimalUtils.setPriceStyle(mContext,maxPrice,R.dimen.price_text_size_14,R.dimen.price_text_size_12,false)));
                }
            }
            if ("".equals(StringUtils.CS(mResponse.getIntroduce()))) {
                mLinearLayout.setVisibility(View.GONE);
            } else {
                mTvNoticeMore.setText(mResponse.getIntroduce());
            }
            ImageLoaderUtils.display(mContext, mProductCover, mResponse.getProductUrl());
            if (!StringUtils.isNull(mResponse.getDiscount())) {
                String discountUrl = mResponse.getDiscount().get(0).getDiscountIcon();
                mHuiText.setVisibility(View.VISIBLE);
                if (!StringUtils.isNull(discountUrl)) {//优惠的图片为null隐藏
                    mHuiImage.setVisibility(View.VISIBLE);
                    ImageLoaderUtils.displayBigPhoto(mContext, mHuiImage, discountUrl);
                } else {
                    mHuiImage.setVisibility(View.GONE);
                    mHuiText.setVisibility(View.GONE);
                }
                mHuiText.setText(StringUtils.CS(mResponse.getDiscount().get(0).getDiscountContent()));
            } else {
                mHuiImage.setVisibility(View.GONE);
                mHuiText.setVisibility(View.GONE);
            }
            if (!StringUtils.isNull(response.getTypeList())) {
                mListData.addAll(response.getTypeList());
                mProductAdapter.notifyDataSetChanged();
            }


            mAddressLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!StringUtils.isNull(mResponse)) {
                        Intent intent = new Intent(mContext, LocationMapActivity.class);
                        intent.putExtra(Constants.FLAG_INTENT_LATITUDE, mResponse.getLat());//经度
                        intent.putExtra(Constants.FLAG_INTENT_LONGITUDE, mResponse.getLng());//维度
                        intent.putExtra(Constants.FLAG_INTENT_ADDRESS, mShortAddress);//地址
                        intent.putExtra(Constants.FLAG_INTENT_GYM_NAME, mGymName);//场馆名称
                        startActivity(intent, false);
                    }
                }
            });
        }
    }

    /**
     * 填充相册的数量
     */

    private void dofullCount() {
        int mCount=0;
        if (!StringUtils.isNull(mImageList)) {
            mCount = mImageList.size();
        }
    }

    private void changeButton(boolean isRefresh) {
        if (mResponse.getIsCollection()) {
            mTitleManager.setRightView(R.mipmap.icon_star_selected, R.mipmap.icon_star_press);
            mCollectAnimotion.stopAnimotion();
        } else {
            if(isRefresh)//已经启动动画就不需要再启动
                return;

            mTitleManager.setRightView(R.mipmap.icon_star_normal, R.mipmap.icon_starblue_normal);
            mCollectAnimotion.startAnimotion();
        }
    }

    /**
     * 是否登录判断跳转
     */
    public void sartActivityIsLogin() {
        if (!DataCenter.getInstance().checkIsLogin()) {
            ToastUtil.showToast(mContext, "请登录后重试");
            startActivity(CodeLoginActivity.class, false);
        } else {
            if (!StringUtils.isNull(mResponse)) {
                if (mResponse.getIsCollection()) {
                    loadingView.show();
                    IUserService.cancelMyCollection(this, Enum.EnumCollect.Product, mResponse.getProductId(), false, new ObjectCallback<Object>() {
                        @Override
                        public void onSuccess(Object response, String message) {
                            mCollectAnimotion.startAnimotion();
                            mResponse.setIsCollection(false);
                            changeButton(false);
                            EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_REFRESH_MY_COURSE, null));
                            ToastUtil.showToast(mContext, message);
                            dialogDis();
                        }

                        @Override
                        public void onErrorT(int code, Object response, String errorMessage) {
                            dialogDis();
                        }

                        @Override
                        public void onHttpErrorCall(int statusCode) {
                            dialogDis();
                        }
                    });
                } else {
                    loadingView.show();
                    IUserService.collect(this, mResponse.getProductId(), Enum.EnumCollect.Product, false, new ObjectCallback<Object>() {
                        @Override
                        public void onSuccess(Object response, String message) {
                            mResponse.setIsCollection(true);
                            mCollectAnimotion.stopAnimotion();
                            changeButton(false);
                            mTitleManager.getmRightView().startAnimation(animation);
                            ToastUtil.showToast(mContext, message);
                            dialogDis();
                        }

                        @Override
                        public void onErrorT(int code, Object response, String errorMessage) {
                            dialogDis();
                        }

                        @Override
                        public void onHttpErrorCall(int statusCode) {
                            dialogDis();
                        }
                    });
                }
            }
        }
    }

    /**
     * EventBus 接收事件
     * 刷新我的信息
     *
     * @param uiEvent
     */
    @Subscribe
    public void toReflashInfo(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_MYINFO)) {
            getProductDetails(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
        UMShareAPI.get(this).release();
        mCollectAnimotion.stopAnimotion();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_product_cover:
                if(StringUtils.isNull(mImageList)){
                    ToastUtil.showToast(mContext,"暂无相册");
                    return;
                }
                Bundle mBundle=new Bundle();
                mBundle.putSerializable(Constants.FLAG_INTENT_VENUEPIC, (Serializable) mImageList);
//                startActivity(ShowImagActivity.class,mBundle,false);
                ActivityUtils.makeScaleLaunch(this,v,mBundle,ShowImagActivity.class);
                break;


            case R.id.iv_img_right:
                //判断是否登录
                sartActivityIsLogin();
                break;

            case R.id.iv_img_right_right:
                if(null==mShareDialog){
                    mShareDialog=new ShareDialog(ProductDetailsActivity.this, R.style.BottomToTopAnim);
                    mShareDialog.setTitle(PicSplit.makeShareTitle(mGymName,mProjectName));
                    String mShareGymUrl= PicSplit.makeShareUrl(PicSplit.S_COURSE_ID,productId,null,null);
                    Log.e("shareUrl",mShareGymUrl);
                    mShareDialog.setTagUrl(mShareGymUrl);
                    mShareDialog.setShareContent(PicSplit.makeSHareContent(mShortAddress,DecimalUtils.setPriceStyle(mContext,minPrice,R.dimen.price_text_size_14,R.dimen.price_text_size_12,true).toString()));
                }
                mShareDialog.show();
                break;
        }
    }
    /**
     * 弹框提示 先支付才能继续支付
     * @param mNotPayOrderId 未支付的订单号
     * @param mOrderType 未支付的订单类型
     */

    private void doMustPay(final String mNotPayOrderId, final int mOrderType) {
        final ComDialog dialog = CommonDialogUtils.dialog(ProductDetailsActivity.this,getSupportFragmentManager(),getString(R.string.str_order_remind), mContext.getString(R.string.order_must_pay), mContext.getString(R.string.str_pay_sub), mContext.getString(R.string.str_cancel));
        dialog.setSubmit(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Bundle mBundle = new Bundle();
                mBundle.putString(Constants.FLAG_INTENT_GYM_ORDER_ID, mNotPayOrderId);
                if(mOrderType==Constants.PRODUCT_ORDER_TYPE){//产品订单
                    mBundle.putInt(Constants.FALG_INTENT_PRODUCT_TAG, Constants.PRODUCT_ORDER_TYPE);//标识是产品订单
                }
                mBundle.putString(Constants.FLAG_INTENT_IS_CONFIRM, Constants.FLAG_INTENT_IS_CONFIRM);//标识是确认订单页面
                mBundle.putString(Constants.FALG_INTENT_FROM_PRODUCT, Constants.FALG_INTENT_FROM_PRODUCT);//标识从产品进入
                startActivity(OrderDetailActivity.class, mBundle, false);

            }
        });
        dialog.setCancel(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void goIsProductPay(String mNoPayOrderId, int mNopayOrderType) {
        doMustPay(mNoPayOrderId,mNopayOrderType);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}

